var router=require('express').Router();
var Note=require('../models/index').note;

module.exports=router;

router.get('/',(req,res)=>{
    var errorArr=req.flash('error');
    var error={};
    errorArr.forEach(err=>{
       Object.assign(error,err);
    });

    res.render('add',{
        title:'Add',
        error:error
    });
});

router.post('/',(req,res,next)=>{
    var body=req.body,now=new Date();
    console.log('body:',body);
    var {title,expiration,desc}=body;
    var error=[];

    if(!title ||　title.length<5　||　title.length>500)error.push({title:'标题长度非法'});
    if(!desc ||　desc.length<5　||　desc.length>2000)error.push({desc:'内容长度非法'});

    expiration=new Date(expiration);

    if(Number.isNaN(expiration.getTime()) || expiration.getTime()<=now.getTime())error.push({expiration:'过期时间非法'});

    if(error.length){
        req.flash('error',error);
        return res.redirect('back');
    }

    new Note({
        title,
        createTime:now,
        expirationTime:expiration,
        desc
    }).save((err)=>{
        if(err)return next(err);
        res.redirect('back');
    });
});